package repository

import (
	"ruanGongKeShe16Zu/db"
	"ruanGongKeShe16Zu/model"
	"ruanGongKeShe16Zu/service/vo"

	"gorm.io/gorm"
)

type ICommentRepository interface {
	Create(comment *model.Comment) (*model.Comment, error)
	SelectById(id int) (*model.Comment, error)
	Update(comment model.Comment, newComment vo.CommentReq) (*model.Comment, error)
	DeleteById(id int) error
	CommentList(req *vo.ListCommentReq) ([]*model.Comment, error)
	SelectByInstrumentID(req *vo.ListCommentReq, id uint) ([]*model.Comment, error)
}

type CommentRepository struct {
	DB *gorm.DB
}

func NewCommentRepository() ICommentRepository {
	return CommentRepository{DB: db.GetDB()}
}

func (o CommentRepository) Create(comment *model.Comment) (*model.Comment, error) {
	if err := o.DB.Create(&comment).Error; err != nil {
		return nil, err
	}
	return comment, nil
}

func (o CommentRepository) SelectById(id int) (*model.Comment, error) {
	var comment model.Comment
	if err := o.DB.First(&comment, id).Error; err != nil {
		return nil, err
	}
	return &comment, nil
}

func (o CommentRepository) Update(comment model.Comment, newComment vo.CommentReq) (*model.Comment, error) {
	if err := o.DB.Model(&comment).Updates(newComment).Error; err != nil {
		return nil, err
	}
	return &comment, nil
}

func (o CommentRepository) DeleteById(id int) error {
	comment, err := o.SelectById(id)
	if err != nil {
		return err
	}
	if err := o.DB.Delete(comment).Error; err != nil {
		return err
	}
	return nil
}

func (o CommentRepository) CommentList(req *vo.ListCommentReq) ([]*model.Comment, error) {
	if req.PageSize != 0 {
		var comments []*model.Comment
		if err := o.DB.Order("created_at desc").Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize).Find(&comments).Error; err != nil {
			return nil, err
		}
		return comments, nil
	}
	var comments []*model.Comment
	if err := o.DB.Find(&comments).Error; err != nil {
		return nil, err
	}
	return comments, nil
}

func (o CommentRepository) SelectByInstrumentID(req *vo.ListCommentReq, id uint) ([]*model.Comment, error) {
	if req.PageSize != 0 {
		var comments []*model.Comment
		if err := o.DB.Where("instrument_id = ?", id).Order("created_at desc").Offset((req.PageNum - 1) * req.PageSize).Limit(req.PageSize).Find(&comments).Error; err != nil {
			return nil, err
		}
		return comments, nil
	}
	var comments []*model.Comment
	if err := o.DB.Where("instrument_id = ?", id).Find(&comments).Error; err != nil {
		return nil, err
	}
	return comments, nil
}
